<?php

namespace App\Services\Base;
use App\Exceptions\BusinessException;
use App\Common\ResponseCode;
use App\Models\Base\Resource;
use App\Models\Role\Role;
use App\Models\Role\RoleResourceBind;
use App\Params\Backend\ResourceListParam;
use App\Params\Backend\ResourceUpdateParam;
use App\Repository\ResourceRepository;
use App\Services\BaseService;

/**
 * 系统资源业务类
 *
 * @author WangBin
 * @date 2021-09-24
 * @package App\Http\Services
 */
class ResourceService extends BaseService
{
    /**
     * 获取资源列表
     *
     * @param
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getList(ResourceListParam $param)
    {
        // 获取所有资源
        return $this->toList(ResourceRepository::getInstance()->getList($param->toArray()), $param->getPage(), $param->getPageSize());
    }

    /**
     * 保存资源
     *
     * @param ResourceUpdateParam $data
     * @return bool
     * @throws BusinessException
     */
    public function update(ResourceUpdateParam $data)
    {
        return ResourceRepository::getInstance()->save($data->toArray(), $data->getResourceId());
    }

    /**
     * 资源详情
     *
     * @param int $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws BusinessException
     */
    public function get(int $id)
    {
        $resource = ResourceRepository::getInstance()->getById($id);
        if(is_null($resource)) {
            throw new BusinessException(ResponseCode::RESOURCE_NOT_FOUND);
        }
        return $resource;
    }

    /**
     * 删除资源
     *
     * @param array $resIds
     * @return mixed
     * @throws
     */
    public function delete(string $resIds)
    {
        $resIdsList = explode(',', $resIds);
        if(empty($resIdsList)) {
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL);
        }
        return Resource::remove($resIdsList);
    }

    /**
     * 停用/启用资源
     *
     * @param int $id
     * @return int
     * @throws BusinessException
     */
    public function enable(int $id)
    {
        $resource = ResourceRepository::getInstance()->getById($id);
        if(is_null($resource)) {
            throw new BusinessException(ResponseCode::RESOURCE_NOT_FOUND);
        }
        $isActive = $resource->is_active == 0 ? 1 : 0;
        return ResourceRepository::getInstance()->save(['is_active' => $isActive], $id);
    }
}
